package com.atguigu.gmall.activity.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.activity.pojo.UserRecode;
import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.activity.SeckillGoods;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
public class SeckillGoodsServiceImpl implements SeckillGoodsService {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 秒杀商品列表
     *
     * @param time
     * @return
     */
    @Override
    public List<SeckillGoods> getSeckillGoods(String time) {

        List<SeckillGoods> seckillGoodsList = redisTemplate.boundHashOps(RedisConst.SECKILL_GOODS + ":"  + time).values();
        return seckillGoodsList;
    }

    /**
     * 秒杀商品详情
     *
     * @param time
     * @param id
     * @return
     */
    @Override
    public SeckillGoods getSeckillGood(String time, String id) {
        SeckillGoods seckillGoods = (SeckillGoods)redisTemplate.boundHashOps(RedisConst.SECKILL_GOODS + ":" + time).get(id);
        return seckillGoods;
    }

    @Autowired
    private RabbitService rabbitService;
    /**
     * 用户排队下单
     *
     * @param time
     * @param skuId
     * @param userId
     * @return
     */
    @Override
    public UserRecode addOrder(String time, String skuId, String userId) {

        // 记录用户的排队信息
        UserRecode userRecode = new UserRecode();
        userRecode.setUserId(userId);
        userRecode.setCreateTime(new Date());
        userRecode.setStatus(1);
        userRecode.setGoodsId(skuId);
        // 时间段
        userRecode.setTime(time);
        // 假设限购数量为1
        userRecode.setNum(1);
        // 将用户的排队信息存入redis中去
        redisTemplate.boundValueOps(RedisConst.SECKILL_USER + userId).set(userRecode);

        // 发送消息进行异步下单
        rabbitService.sendMessage(
                "seckill_exchange",
                "seckill.order.add",
                JSONObject.toJSONString(userRecode));

        // 返回用户排队的结果
        return userRecode;
    }

    /**
     * 查询用户的排队信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserRecode getUserRecode(String userId) {

        return (UserRecode)redisTemplate.boundValueOps(RedisConst.SECKILL_USER + userId).get();
    }

}
